var upload = null;
$.tmUpload = function(options){
	var opts = $.extend({},$.tmUpload.defaults,options);
	var settings = {
		flash_url : basePath + "/js/upload/swfupload.swf",
		upload_url: opts.url,	  //上传的服务器的地址,JSP文件或者Controller类
		post_params: opts.params, //需要传递到后台的参数
		file_size_limit : opts.limitSize,//上传文件的大小限制
		file_types : opts.fileTypes,//格式过滤
		file_types_description :opts.fileTypesDes,
		file_upload_limit : opts.uploadLimit,  //配置上传个数
		file_queue_limit : opts.queueLimit,//代表不限制
		file_post_name : opts.postName,
		debug: false,
		
		// Button settings
		button_image_url: opts.btnImage,
		button_width: opts.btnWidth,
		button_height: opts.btnHeight,
		button_placeholder_id: opts.btnId,
		//button_text: '<span class="theFont">浏览</span>',
		//button_text_style: ".theFont { font-size: 16; }",
		button_text_left_padding: 12,
		button_text_top_padding: 3,
		button_action : (opts.multiple? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE),
		
		//文件上传队列的预设方法
		file_queued_handler : function(file){
			tm_append_uploaditem(file);
		},
		
		//文件上传完毕的预设方法
		file_dialog_complete_handler : function(numFilesSelected, numFilesQueued){
			$("#aspupload").find(".bar_total").html("共"+numFilesSelected+"个文件 ，还剩余<span class='number'>"+numFilesQueued+"</span>个");
			this.startUpload();
		},
		
		//文件上传队列如果出错的预设方法
		file_queue_error_handler : fileQueueError,
		
		
		upload_start_handler : function(file){
			$("#"+file.id).find(".prepared").hide();
			$("#"+file.id).find(".loading").show();
		},
		
		/**
		 * 上传过程进行中的预设方法
		 */
		upload_progress_handler : function(file, bytesLoaded, bytesTotal){
			var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
			$("#"+file.id).find(".up-prograss").width(percent+"%");
			$("#"+file.id).find(".filesize").text(tm_countFileSize(bytesLoaded)+" / "+tm_countFileSize(bytesTotal));
			
		},
		upload_success_handler : function(file, serverData){
			if(opts.callback)opts.callback(serverData,file);
			tm_hide_upload();
		},
		upload_complete_handler : function(file){
			$("#"+file.id).fadeOut("slow",function(){
				$(this).remove();
				var length = $("#uploaditembox").find("li").length;
				$("#aspupload").find(".bar_total").find(".number").text(length);
				 tm_hide_upload();
			});
			this.startUpload();
		},
		upload_error_handler : uploadError
	};
	
	//新建SWFUpload实例，只要调用该组件的页面一加载，就会执行这一行代码了。
	upload = new SWFUpload(settings);
};



$.tmUpload.defaults = {
	url:"/yunpan/upload.jsp",//上传的路径
	limitSize:"1000 MB",/*MB*///上传文件吸纳子的大小
	params:{},//传递给服务器的参数，key-value
	fileTypes:"*.*",//过来文件选择的类型*.jpg;*.gif
	fileTypesDes:"所有文件",
	postName:"file",
	uploadLimit:100,
	queueLimit:0,
	multiple : true,//控制你选择文件是选择单个还是多个
	btnId:"tmupload",//按钮
	btnImage: basePath + "/js/upload/btn_wj.jpg",//对应的上传图标
	btnWidth:100,//图标的宽度
	btnHeight:32,//图标的高度
	callback:function(serverData,file){//上传成功的回调方法
		
		
	}
};
 
 
 //统计文件的大小
 function tm_countFileSize(size) {
	var fsize = parseFloat(size, 2);
	var fileSizeString;
	if (fsize < 1024) {
		fileSizeString = fsize.toFixed(2) + "B";
	} else if (fsize < 1048576) {
		fileSizeString = (fsize / 1024).toFixed(2) + "KB";
	} else if (fsize < 1073741824) {
		fileSizeString = (fsize / 1024 / 1024).toFixed(2) + "MB";
	} else if (fsize < 1024 * 1024 * 1024 * 10) {
		fileSizeString = (fsize / 1024 / 1024 / 1024).toFixed(2) + "GB";
	} else {
		fileSizeString = "0B";
	}
	return fileSizeString;
};

//文件开始上传异常捕获信息
function fileQueueError(file, errorCode, message) {
	tm_append_uploaditem(file);
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			$filename.html("您已达到上传限制 您最多能选择 " + (message > 1 ? "上传 " + message + " 文件." : "一个文件."));
			return;
		}
		var $filename = $("#"+file.id).find(".filename");
		switch (errorCode) {
    		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
    			$filename.html("<span class='red'>文件尺寸过大," + file.name+"</span>");
    			break;
    		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
    			$filename.html("<span class='red'>零字节文件, 文件名: " + file.name+"</span>");
    			break;
    		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
    			$filename.html("<span class='red'>不支持的文件类型, 文件名: " + file.name+"</span>");
    			break;
    		default:
    			$filename.html("<span class='red'>未知错误</span>");
    			break;
    	}
		$("#"+file.id).fadeOut(8000,function(){$(this).remove(); $("#aspupload").find(".bar_total").find(".number").text($("#uploaditembox").find("li").length);});
	} catch (ex) {
        this.debug(ex);
    }
};

/**
 * 出错信息的回调方法
 * file： 文件对象（聚合）
 * errorCode： 错误码
 * message：
 */
function uploadError(file, errorCode, message) {
	try {
		var $filename = $("#"+file.id).find(".filename");
		switch (errorCode) {
    		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
    			$filename.html("<span class='red'> HTTP错误, 文件名: " + file.name+"</span>");
    			break;
    		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
    			$filename.html("<span class='red'>上传失败</span>");
    			break;
    		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
    			$filename.html("<span class='red'>服务器 (IO) 错误</span>");
    			break;
    		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
    			$filename.html("<span class='red'>安全错误</span>");
    			break;
    		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
    			$filename.html("<span class='red'>超出上传限制.</span>");
    			break;
    		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
    			$filename.html("<span class='red'>无法验证.  跳过上传.</span>");
    			break;
    		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
    			$filename.html("<span class='red'>取消</span>");
    			break;
    		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
    			$filename.html("<span class='red'>停止</span>");
    			break;
    		default:
    			$filename.html("<span class='red'>未处理的错误: " + errorCode+"</span>");
    			break;
		}
		//8秒后隐藏
		$("#"+file.id).fadeOut(8000,function(){$(this).remove(); $("#aspupload").find(".bar_total").find(".number").text($("#uploaditembox").find("li").length);});
	} catch (ex) {
        this.debug(ex);
    }
}


//空判断
function isEmpty(val) {
	val = $.trim(val);
	if (val == null)
		return true;
	if (val == undefined || val == 'undefined')
		return true;
	if (val == "")
		return true;
	if (val.length == 0)
		return true;
	if (!/[^(^\s*)|(\s*$)]/.test(val))
		return true;
	return false;
}

 /*折叠上传框*/
 function tm_expand_upload(obj){
	if($(obj).hasClass("shrink")){
		$(obj).removeClass("shrink").addClass("enlarge");
		$("#mainloadarea").animate({"height":0});
	}else{
		$(obj).removeClass("enlarge").addClass("shrink");
		$("#mainloadarea").animate({"height":345});
	}
 }

//关闭上传框的话就关闭上传的队列
function tm_expand_close(obj){
	$("#mainloadarea").empty();
	$("#aspupload").animate({"height":0},function(){
		$(this).remove();
	});
	upload.cancelQueue(); //取消上传队列
}